package cn.hxzy.common.filter;


import cn.hxzy.common.domain.User;
import cn.hxzy.common.util.JwtUtils;
import cn.hxzy.common.util.ThreadLocalUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//每一个servlet请求，只会执行一次
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            //获取当前请求的url地址
            String url = request.getRequestURI();
            //如果当前请求不是登录请求，则需要进行token验证
            if (!url.equals("/user/login") && !url.equals("/user/getOpenId") && !url.equals("/goodsCategories/categoryList") && !url.equals("/goods/goodsListByCategoryId") && !url.equals("/goods/goodsList")) {
                validateToken(request,response);
            }
        //登录请求不需要验证token
        doFilter(request, response, filterChain);
    }


    /**
     * 验证token
     *
     * @param request
     */
    private void validateToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //从头部获取token信息
        String token = request.getHeader("Authorization");
        System.out.println("token=========================:"+token);

        //如果请求头部没有获取到token，则从请求的参数中进行获取
        if (StringUtil.isNullOrEmpty(token)) {
            token = request.getParameter("Authorization");

        }
        if (StringUtil.isNullOrEmpty(token)) {
            //token不存在，返回401
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        //如果存在token，则从token中解析出用户名
        User user=null;
        String loginUserStr = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            Claims claims = JwtUtils.getClaimsFromToken(token);
            loginUserStr = claims.getSubject();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            user = mapper.readValue(loginUserStr, User.class);

        } catch (Exception e) {
            //token解析失败，返回401
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        ThreadLocalUtil.setUser(user);
    }

}
